<template>
  <div v-if="files && files.length > 0">
    <div class="header-self-wrap">
      <div class="header-self-content">
        <Attachments
          :before-upload="handleBeforeUpload"
          :file-list="files"
          :hide-upload="false"
          :http-request="handleHttpRequest"
          :items="files"
          drag
          @delete-card="handleDeleteCard"
          @upload-drop="handleUploadDrop"
        />
      </div>
    </div>
    <!-- 引用 -->
    <!-- <div
      class="m-3 flex justify-between rounded-xl p-3"
      style="background-color: #e1ffc7"
    >
      <div>
        <span>引用内容:</span>
        我是引用内容！！！！！！！！
      </div>
      <div class="cursor-pointer">X</div>
    </div> -->
  </div>
</template>

<script setup lang="ts">
import type { SelfFilesCardProps } from '../type';

import { uploadFiles } from '#/api/agent/upload';

const files = defineModel<SelfFilesCardProps[]>('modelValue');

// 文件上传前校验
function handleBeforeUpload(file: File) {
  if (file.size > 1024 * 1024 * 2) {
    ElMessage.error('文件大小不能超过 2MB!');
    return false;
  }
}

// 文件上传
async function handleHttpRequest(options: { file: any | File }) {
  const { file } = options;

  const formData = new FormData();
  formData.append('files', file);
  ElMessage.info('上传中...');
  const data = await uploadFiles(formData);

  setTimeout(() => {
    const res = {
      message: '文件上传成功',
      fileName: file.name,
      uid: file?.uid || '',
      fileSize: file.size,
      imgFile: file,
    };
    files.value?.push({
      id: files.value.length,
      uid: res.uid,
      name: data?.success_files[0]?.file_name,
      fileSize: data?.success_files[0]?.size,
      url: data?.success_files[0]?.url,
      imgFile: res.imgFile,
      showDelIcon: true,
      imgVariant: 'square',
    });

    ElMessage.success('上传成功');
  }, 1000);
}

// 文件删除
function handleDeleteCard(item: SelfFilesCardProps) {
  files.value = files.value?.filter(
    (items: SelfFilesCardProps) => items.id !== item.id,
  );
  ElMessage.success('删除成功');
}

// 文件拖拽上传
async function handleUploadDrop(files: File[]) {
  if (files && files.length > 0) {
    if (files[0]?.type === '') {
      ElMessage.error('禁止上传文件夹！');
      return false;
    }

    for (const file of files) {
      await handleHttpRequest({ file });
    }
  }
}
</script>
<style scoped lang="scss">
.header-self-wrap {
  display: flex;
  flex-direction: column;
  height: 100px;
  padding: 16px;

  .header-self-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 30px;
    padding-bottom: 8px;
  }
}

:deep(.el-upload-dragger) {
  background-color: white !important;
}
</style>
